package future;

import java.util.concurrent.*;

/**
 * Created by brossdong on 2018/1/24.
 * future和callable的使用
 */
public class UseFuture implements Callable<String>{

    private String para;

    public UseFuture(String para) {
        this.para = para;
    }

    /**
     * 这里是业务逻辑
     * @return
     * @throws Exception
     */
    public String call() throws Exception {
        Thread.sleep(5000);
        String ret = this.para + "处理完成";
        return ret;
    }

    public static void main(String[] args) throws Exception {
        String queryStr = "queryStr";
        //构造FutureTask类,并且传入需要真正执行的处理业务逻辑的类,该类一定实现了Callable接口
        FutureTask<String> future1 = new FutureTask<String>(new UseFuture(queryStr));
        FutureTask<String> future2 = new FutureTask<String>(new UseFuture(queryStr));

        //创建一个固定线程组
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future ret1 = executor.submit(future1);
        Future ret2 = executor.submit(future2);

        System.out.println("请求完毕");

        try {
            System.out.println("处理业务逻辑");
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("数据:" + ret1.get());
        System.out.println("数据:" + ret2.get());

        executor.shutdown();
    }
}
